package org.arabidopsis.ahocorasick;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;


public class IsContains {
    public static boolean isContains(String key, String utf8filepath) {
        key = key.toLowerCase();
        IsContains ic = new IsContains();
        AhoCorasick tree = ic.initTree(utf8filepath);
        return ic.search(key, tree);
    }

    private AhoCorasick initTree(String file) {
        AhoCorasick tree1 = new AhoCorasick();
        try {
            BufferedReader file1 = new BufferedReader(
                    new InputStreamReader(new FileInputStream(new File(file)), StandardCharsets.UTF_8));

            String s = file1.readLine();
            int i = 0;
            while (s != null) {
                if (i == 0 && s.startsWith("﻿")) {
                    s = s.substring(1);
                }
                i++;

                s = s.toLowerCase();
                tree1.add(s.getBytes(), s);
                s = file1.readLine();
            }
            file1.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        tree1.prepare();
        return tree1;
    }

    private boolean search(String arg, AhoCorasick tree) {
        Iterator<SearchResult> searcher = tree.search(arg.getBytes());
        while (searcher.hasNext()) {
            SearchResult result = searcher.next();
            Iterator it = result.getOutputs().iterator();
            if (it.hasNext()) {
                return true;
            }
        }


        return false;
    }
}